<?php

	class source
	{

		var $fw		= null;
		var $sec	= null;

		function source(&$framework, &$security)
		{

			$this->fw	= &$framework;
			$this->sec	= &$security;

			$this->fw->pc_item('Configuration', 'Manage your configuration', 'index.php?what=config');

			$this->fw->js[] = 'config.js';

			switch($this->fw->do)
			{

				case 'management':
					$this->show_management_options();
					break;

				// delete movies from database that arnt being used
				case 'cleanup':
					$this->process_cleanup();
					break;

				// remove all movie data
				case 'truncate':
					$this->process_truncate();
					break;

				// optimize & repair the movies db (mm tables only)
				case 'repair':
					$this->repair_db();
					break;

				// create a backup of the database (sql)
				case 'backup':
					$this->backup_db();
					break;

				// download the configuration file
				case 'config':
					$this->download_configuration();
					break;

				// update all movies details from imdb.com!
				case 'update':
					$this->process_update();
					break;

				// ajax: update the movie in the counter
				case 'process_update':
					$this->process_update_ajax();
					break;

				// save the option form
				case 'process':
					$this->process_form();
					break;

				default:
					$this->show_form();
					break;

			}

		}

		function show_management_options()
		{
			$this->fw->template = 'config.management.tpl';
			$this->fw->pc_item('Management', 'Advanced configuration options', 'index.php?what=management');
		}

		function process_update_ajax()
		{
			$this->fw->main_template = null; // turns off smarty (ajax output)
			$counter = (int)$_GET['c'];
			// lets figure out what movie we are processing
			$sql	= $this->fw->_pq("SELECT `movie_id`, `movie_imdb`, `movie_title`, `movie_year` FROM `#__movies` ORDER BY `movie_id` LIMIT %s, 1", $counter);
			$result	= mysql_query($sql) or die(mysql_error());

			if($row = mysql_fetch_assoc($result)) {
				// update the movie!
				if($this->fw->update_movie($row['movie_id'])) {
					echo 'success|';
				} else {
					// could not update
					echo 'failed|';
				}
				echo $row['movie_id'] .'|'. $row['movie_imdb'] .'|'. $row['movie_title'] .'|'. $row['movie_year'];
			} else {
				// no data left
				echo 'finished';
			}
		}

		// update all the movies in the database
		function process_update()
		{
			// update timestamp
			$this->fw->save_config('timestamp_movies_update', time());

			$this->fw->pc_item('Management', 'Advanced configuration options', 'index.php?what=management');
			$this->fw->pc_item('Update movie database', 'Update all the movies in your database from imdb', 'index.php?what=config&do=update');
			$this->fw->js[] = 'ajax.js';
			$this->fw->template = 'config.update.tpl';
			//$sql	= $this->fw->_pq("SELECT `movie_id`, `movie_imdb` FROM `#__movie` ORDER BY `movie_id` ASC");
		}

		// finds all the movies that arn't in either someones collection or wishlist and removes them and all trace of them (except the cache file)
		function process_cleanup()
		{
			// lets get our movies
			$sql	= $this->fw->_pq("SELECT `m`.`movie_id`, `m`.`movie_imdb`, `m`.`movie_image_name`
									    FROM `#__movies` AS `m`
									  LEFT OUTER
									    JOIN `#__own` AS `o`
									      ON `m`.`movie_id` = `o`.`movie_id`
									  LEFT OUTER
									    JOIN `#__wishlist` AS `w`
									      ON `m`.`movie_id` = `w`.`movie_id`
									   WHERE `o`.`movie_id` IS NULL
									     AND `w`.`movie_id` IS NULL
									  GROUP BY `m`.`movie_id`");
			$result	= mysql_query($sql) or die(mysql_error());
			$num	= mysql_num_rows($result);

			// loop through each movie and remove it
			while($row = mysql_fetch_assoc($result)) {
				$id[]	= $row['movie_id'];
				// remove cache
				$this->fw->unlink(_BASE_PATH . $this->fw->config['directory_imdb_cache'] . $row['movie_imdb'] .'.title');
				// remove image file
				if($row['movie_image_name'] != null) {
					$this->fw->unlink(_BASE_PATH . $this->fw->config['directory_imdb_image'] . $row['movie_image_name']);
				}
			}

			if(isset($id) && is_array($id)) {
				$ids = implode(',', $id);
				// we do not need to delete from _own or _wishlist (its impossible for them to have a record at this point)
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__borrow` WHERE `movie_id` IN (%s)", $ids);
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__comment` WHERE `movie_id` IN (%s)", $ids);
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__lnk_movie_actors` WHERE `movie_id` IN (%s)", $ids);
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__lnk_movie_directors` WHERE `movie_id` IN (%s)", $ids);
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__lnk_movie_genre` WHERE `movie_id` IN (%s)", $ids);
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__lnk_movie_writers` WHERE `movie_id` IN (%s)", $ids);
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__ratings` WHERE `movie_id` IN (%s)", $ids);
				// delete actual movie last
				$sqls[]	= $this->fw->_pq("DELETE FROM `#__movies` WHERE `movie_id` IN (%s)", $ids);

				foreach($sqls as $sql) {
					$result	= mysql_query($sql) or die(mysql_error());
				}
				unset($ids, $sqls, $sql, $result);
			}

			// clean any orphaned cast members
			$this->_clean_cast();
			// fix up the genre count
			$this->fw->update_genre_movie_count();

			$_SESSION['msg'] = $num .' movie(s) were removed from the database';
			header('location: index.php?what=config');
			exit;

		}

		// remove all movies, collections, wishlists, cache & imdb images, and any related data
		function process_truncate()
		{
			// this can only be run in developer mode
			if($this->fw->config['developer'] != '1') {
				header('location: index.php?what=config');
				exit;
			}
			// clean the database
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__borrow`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__cast`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__comment`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__lnk_movie_actors`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__lnk_movie_directors`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__lnk_movie_genre`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__lnk_movie_writers`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__movies`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__own`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__ratings`");
			$sqls[]	= $this->fw->_pq("TRUNCATE TABLE `#__wishlist`");
			$sqls[]	= $this->fw->_pq("UPDATE `#__genre` SET `genre_movie_count` = 0;"); // reset the movie_count
			$sqls[]	= $this->fw->_pq("UPDATE `#__member` SET `movie_count` = 0;");
			foreach($sqls as $sql) {
				$result	= mysql_query($sql) or die(mysql_error());
			}
			// clear the cache directory
			$path = _BASE_PATH . $this->fw->config['directory_imdb_cache'];
			$this->fw->clean_dir($path);
			// clear the images
			$path = _BASE_PATH . $this->fw->config['directory_imdb_image'];
			$this->fw->clean_dir($path);
			// we are done
			$_SESSION['msg'] = 'Successfully truncated';
			header('location: index.php?what=config');
			exit;

		}

		// backup the database into an sql file, and zip it!
		function backup_db()
		{

			$output = "# Movie Manager 2005 MySQL-Dump\n\n\n";

			$tables = $this->fw->db_get_tables();

			// loop through the tables
			foreach($tables as $table)
			{

				// comment our table
				$output .= "#\n# Saving Table `". $table ."`\n#\n\n";

				// remove the table if it exists
				$output .= "DROP TABLE IF EXISTS `". $table ."`;\n\n";

				// generate the 'CREATE TABLE' sql
				$sql	= $this->fw->_pq("SHOW CREATE TABLE `". $table ."`;");
				$result	= mysql_query($sql) or die(mysql_error());

				$output .= str_replace("\n", null, mysql_result($result, 0, 1)) .";\n\n";

				unset($sql, $result);

				// list of fields within this table
				$sql	= $this->fw->_pq("SHOW COLUMNS FROM `". $table ."`;");
				$result	= mysql_query($sql) or die(mysql_error());

				$fields_num	= mysql_num_rows($result);

				unset($sql, $result);

				$sql	= $this->fw->_pq("SELECT * FROM `". $table ."`;");
				$result	= mysql_query($sql) or die(mysql_error());

				if(mysql_num_rows($result) == 0)
				{

					$output .= "# No ouput data for table: `". $table ."`\n\n";

				}
				else
				{

					$output .= "# ". mysql_num_rows($result) ." records found for `". $table ."`\n\n";;

				}

				while($row = mysql_fetch_row($result))
				{

					$output .= "INSERT INTO `". $table ."` VALUES (";

					for($i = 0; $i < $fields_num; $i++)
					{

						$value = addslashes($row[$i]);
						$value = str_replace("\n", '\n', $value);

						$output .= "'". $value ."',";

					}

					$output = substr($output, 0, -1);

					$output .= ");\n";

				}

				unset($sql, $result);

				$output .= "\n# -------------------------------------------\n\n";

			}

			header('Content-Disposition: attachment; filename="backup.sql"');
			header('content-type: plain/text');
			header('content-length: '. strlen($output));
			echo $output;
			exit;

		}

		// repair and optimize the database
		function repair_db()
		{

			// get all movies with invalid data
			$sql	= $this->fw->_pq("SELECT `movie_id` FROM `#__movies` WHERE `movie_title` = ''");
			$result = mysql_query($sql) or die(mysql_error());

			// loop though and remove any potential orphaned records
			while($row = mysql_fetch_row($result)) {
				$id = (int)$row[0];
				$sql	= array();
				$sql[]	= "DELETE FROM `#__borrow` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__comment` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__lnk_movie_actors` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__lnk_movie_directors` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__lnk_movie_genre` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__lnk_movie_writers` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__own` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__ratings` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__wishlist` WHERE `movie_id` = ". $id;
				$sql[]	= "DELETE FROM `#__movies` WHERE `movie_id` = ". $id;
				foreach($sql as $v) {
					$result = mysql_query($v) or die(mysql_error());
				}
			}

			$this->_clean_cast();

			$tables = $this->fw->db_get_tables();

			if($tables !== false)
			{

				$sql	= $this->fw->_pq("OPTIMIZE TABLE `". implode("`, `", $tables) ."`;");
				$result	= mysql_query($sql) or die(mysql_error());

				$_SESSION['msg'] = 'Database successfully optimized';

			}

			header('location: index.php?what=config');
			exit;

		}

		// deliver the configuration.php to the user for download, as a php file
		function download_configuration()
		{

			// headers
			header('content-type: plain/text');
			header('content-disposition: attachment; filename="configuration.php"');
			header('content-length: '. filesize('includes/configuration.php'));

			readfile('includes/configuration.php');
			exit;

		}

		function process_form()
		{

			// Simply loop though the values

			// Post elements we dont want to save
			$exclude	= array('what', 'do', 'tabs_select');

			foreach($_POST as $k=>$v)
			{

				if(!in_array($k, $exclude) && substr($k, 0, 1) !== '_') // check our exclude array, or if the key starts with an _ =--
				{

					$this->fw->save_config($k, $v);

				}

			}

			$_SESSION['msg']	= 'Configuration Successfully Updated';
			header('location: index.php?what=config'. (isset($_POST['tabs_select']) && !empty($_POST['tabs_select']) ? '#'. $_POST['tabs_select'] : null));
			exit;

		}

		function show_form()
		{

			$this->fw->template = 'config.form.tpl';

			// Form data
			$this->fw->content['templates']	= $this->fw->get_available_templates();

		}

		// find and delete any cast member records that arn't related to directors, writers or actors
		function _clean_cast()
		{
			$sql	= $this->fw->_pq("SELECT `c`.`name_id`
									    FROM `#__cast` AS `c`
									  LEFT OUTER
									    JOIN `#__lnk_movie_actors` AS `a`
									      ON `c`.`name_id` = `a`.`name_id`
									  LEFT OUTER
									    JOIN `#__lnk_movie_directors` AS `d`
									      ON `c`.`name_id` = `d`.`name_id`
									  LEFT OUTER
									    JOIN `#__lnk_movie_writers` AS `w`
									      ON `c`.`name_id` = `w`.`name_id`
									   WHERE `a`.`name_id` IS NULL
									     AND `d`.`name_id` IS NULL
									     AND `w`.`name_id` IS NULL
									  GROUP BY `c`.`name_id`");
			$result	= mysql_query($sql) or die(mysql_error());
			while($row = mysql_fetch_row($result)) {
				$id[] = $row[0];
			}

			if(isset($id) && is_array($id)) {
				$ids = implode(',', $id);
				$sql	= $this->fw->_pq("DELETE FROM `#__cast` WHERE `name_id` IN (%s)", $ids);
				$result	= mysql_query($sql) or die(mysql_error());
			}
			return true;
		}

	}

?>